﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WyUnity.Data.DataAccess;

namespace DAL_13_0
{

    public class BillNo
    {
        string _trantype;
        public BillNo(string trantype)
        {
            _trantype = trantype;
        }
        public string GetNewNumber(DbSession db, bool isSave)
        {
            return GetNewNumber(db, DateTime.Today, isSave);
        }
        public string GetNewNumber(DbSession db, DateTime bizDate, bool isSave)
        {
            var billno = string.Empty;
            var noDefineList = db.QueryList<Entities.SysBillNumber>(Entities.SysBillNumber.pID == _trantype, Entities.SysBillNumber.pInd.Arc);
            foreach (var d in noDefineList)
            {
                switch (d.NumType)
                {
                    //固定字符串
                    case 1:
                        billno += d.Format;
                        break;
                    //日期
                    case 2:
                        billno += bizDate.ToString(d.Format);
                        break;
                    //顺序号
                    case 4:
                        billno += GetCurNo(db, 0, isSave);
                        break;
                    //年度相关序号
                    case 5:
                        billno += GetCurNo(db, bizDate.Year, isSave).ToString(d.Format);
                        break;
                    //月度相关序号
                    case 6:
                        billno += GetCurNo(db, bizDate.Year * 1000 + bizDate.Month, isSave).ToString(d.Format);
                        break;
                    //天相关序号
                    case 7:
                        billno += GetCurNo(db, bizDate.Year * 100000 + bizDate.Month * 100 + bizDate.Day, isSave).ToString(d.Format);
                        break;
                    default:
                        throw new Exception("单据编号类型(" + d.NumType + ")不存在");
                }
            }
            return billno;

        }

        private int GetCurNo(DbSession db, int key, bool isSave)
        {
            var cur = db.QuerySingle<Entities.SysBillNumberCurNo>(Entities.SysBillNumberCurNo.pID == _trantype & Entities.SysBillNumberCurNo.pKey == key);
            if (cur == null)
            {
                cur = new Entities.SysBillNumberCurNo { ID = _trantype, Key = key, CurNo = 1 };

                db.Insert(cur);
            }

            var curno = cur.CurNo;

            if (isSave)
            {
                cur.CurNo += 1;
                db.Update(cur);
            }

            return curno;
        }
    }
}
